package com.syqc.videos

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import autodispose2.autoDispose
import com.syqc.comlib.auto.AutoDisposeViewModel
import com.syqc.comlib.utils.AppContext
import com.syqc.comlib.utils.FileUtil
import com.syqc.comlib.utils.GsonUtil
import com.syqc.comlib.utils.getVideoPath
import com.syqc.entity.HistoryVideo
import com.syqc.entity.VideoState
import com.syqc.monitor.download.DownCallback
import com.syqc.monitor.download.DownLoadUtil
import com.syqc.net.ServiceHelper
import com.syqc.utils.UrlUtil
import com.syqc.utils.VideoHostUtil
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.disposables.Disposable
import java.util.concurrent.TimeUnit


enum class DownState {
    UpQuery, Upload, UploadFail,
    UpProgressSuccess, UpProgress, UpProgressFail,
    UpCancel, UpCancelFail,
    DownStart, DownProgress, DownSuccess, DownFail
}

class HistoryVideoViewModel : AutoDisposeViewModel() {
    var videoHost: String = ""
    var carId: String = ""
        set(value) {
            field = value
            if (value.isNotEmpty()) {
                val host = VideoHostUtil.getVideoHost(value)
                videoHost = VideoHostUtil.getHost(host)
            }
        }
    var history: HistoryVideo.Result? = null

    //播放路径
    private var playPath = ""
    fun getPlayPath() = playPath

    private val _uploadLive = MutableLiveData<DownState>()
    val uploadLive: LiveData<DownState> = _uploadLive

    //状态描述
    private var upState = ""

    //fd
    var jd = ""
    var upSize = ""

    //查询状态
    fun getUpState() = upState

    private var downState = DownState.UpQuery

    fun getDownState() = downState

    //通道下标
    var tmnPass: Int = 0

    var isChangeTime = false

    //传入的历史视频
    private val relust = mutableListOf<HistoryVideo.Result>()
    private val _resultLive = MutableLiveData<MutableList<HistoryVideo.Result>>()
    val resultLive: LiveData<MutableList<HistoryVideo.Result>> = _resultLive

    fun setResult(relust: MutableList<HistoryVideo.Result>) {
        this.relust.clear()
        this.relust.addAll(relust)
        _resultLive.postValue(relust)
    }

    fun search(key: Int) {
        if (key == 0) {
            _resultLive.postValue(relust)
            return
        }

        val values = relust.filter { it.channel == key }

        _resultLive.postValue(values.toMutableList())
    }

    fun uploadFtp(start: String, end: String, videoType: String, isChange: Boolean) {
        isChangeTime = isChange
        _uploadLive.postValue(DownState.UpQuery)
        ServiceHelper.getRepository().getVideoState(getUpload(start, end, videoType))
            .autoDispose(this)
            .subscribe({
                val result = GsonUtil.formObject<VideoState>(it)
                //成功
                if (result.state == "0") {
                    startTime()
                    downState = DownState.Upload

                } else {
                    val state = result.state ?: ""
                    upState = UrlUtil.getLoadFtp(state)
                    downState = DownState.UploadFail

                }
                _uploadLive.postValue(downState)
            }, error)
    }

    private fun getUpload(start: String, end: String, videoType: String): String {

        if (history == null) return ""
        val params = "$videoHost/ftp.upload.${history!!.fileId}.@$carId." +
                "${history!!.channel}.${start.substring(2)}." +
                "${end.substring(2)}.${history!!.alarmFlag}.${history!!.avType}." +
                "${history!!.streamType}.${history!!.storeType}.${if (isChangeTime) 0 else history!!.fileSize}"

        return if (videoType.isEmpty()) params else "$params.$videoType"
    }

    /**
     * 获取文件上传情况
     *
     * @return
     */
    private fun getUploadState(): String {
        if (history == null) return ""
        return "$videoHost/ftp.result.${history!!.fileId}"
    }

    private var subscribe: Disposable? = null
    fun startTime() {
        subscribe?.dispose()
        subscribe = Flowable.interval(0, 3, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .autoDispose(this)
            .subscribe {
                getUploadProgress()
            }
    }

    /**
     * 获取加载进度
     *
     */
    private fun getUploadProgress() {
        ServiceHelper.getRepository().getVideo(getUploadState())
            .autoDispose(this)
            .subscribe({
                val result = GsonUtil.formObject<VideoState>(it)

                //成功
                downState = when (result.state) {
                    "0" -> {
                        subscribe?.dispose()
                        downLoadVideo(result.url)
                        DownState.UpProgressSuccess
                    }

                    "97" -> {
                        upState = UrlUtil.getLoadFtp(result.state ?: "")
                        DownState.UpProgress
                    }

                    "98" -> {
                        val size = result.size

                        val sizeFormat = FileUtil.formatFileSize(result.size ?: 0)
                        if (size == null) {
                            jd = "--%"
                            upSize = "--"
                        } else {
                            jd = if (isChangeTime){
                                "--%"
                            }else{
                                "${result.jd ?: "00"}%"
                            }
                            upSize = sizeFormat
                        }

                        upState = UrlUtil.getLoadFtp(result.state ?: "")
                        DownState.UpProgress
                    }

                    else -> {
                        upState = UrlUtil.getLoadFtp(result.state ?: "")
                        DownState.UpProgressFail
                    }
                }
                _uploadLive.postValue(downState)

            }, error)
    }


    /**
     * 控制文件FTP上传
     *
     * @param control 0暂停上传　1继续上传　2取消上传
     */
    fun uploadControl(control: String = "2") {
        subscribe?.dispose()
        ServiceHelper.getRepository()
            .getVideoState("$videoHost/ftp.ctr.${history!!.fileId}.$control")
            .autoDispose(this)
            .subscribe({
                val result = GsonUtil.formObject<VideoState>(it)
                //成功
                downState = if (result.state == "0") {
                    DownState.UpCancel
                } else {
                    upState = UrlUtil.getLoadFtp(result.state ?: "")
                    DownState.UpCancelFail
                }
                _uploadLive.postValue(downState)
            }, error)
    }

    private val videoPath by lazy { getVideoPath(AppContext.getAppContext()) }
    var downProgress = ""
    private fun downLoadVideo(url: String?) {
        if (url == null) return


        DownLoadUtil.downloadVideo(url, videoPath.path, object : DownCallback {
            override fun onStart() {
                _uploadLive.postValue(DownState.DownStart)
            }

            override fun onLoading(total: Long, progress: Long) {
                val progressFloat = progress / total.toFloat() * 100.0
                val progressInt = progressFloat.toInt()
                downProgress = "$progressInt"
                _uploadLive.postValue(DownState.DownProgress)
            }



            override fun onSuccess(fileName: String) {
                val oldPath = videoPath.path + "/" + fileName
                DownLoadUtil.saveVideoToSystemAlbum(oldPath, AppContext.getAppContext())
                playPath = oldPath
                _uploadLive.postValue(DownState.DownSuccess)

            }

            override fun onFailure(e: Throwable) {
                _uploadLive.postValue(DownState.DownFail)
            }
        })
    }

}